#include "commonpage.h"
#include "ui_commonpage.h"

#include "listitembox.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

CommonPage::CommonPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CommonPage)
{
    ui->setupUi(this);

    ui->addLocalBtn->hide();  // 隐藏加载本地音乐的按钮
    ui->pageMusicList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  // 关闭水平滚动条

    connect(ui->playAllBtn, &QPushButton::clicked, this, [=](){
        // 点击播放所有按钮之后，通知MusicPlayer播放当前page页面中的所有歌曲
        emit playMusicByPageAndIndex(this, 0);
    });

    connect(ui->pageMusicList, &QListWidget::doubleClicked, this, [=](const QModelIndex &index){
        // 鼠标双击后，发射信号告诉MusicPlayer，播放this页面中被双击的歌曲
        emit playMusicByPageAndIndex(this, index.row());
    });
}

CommonPage::~CommonPage()
{
    delete ui;
}

void CommonPage::setCommonPageTitle(const QString &title)
{
    ui->pageTitle->setText(title);
}

void CommonPage::setCommonPageImage(const QPixmap &image)
{
    ui->musicImageLabel->setPixmap(QPixmap(image));
    ui->musicImageLabel->setScaledContents(true);
}

void CommonPage::showAddLocalBtn()
{
    ui->addLocalBtn->show();
}

void CommonPage::setPageType(PageType pageType)
{
    this->pageType = pageType;
}

void CommonPage::addMusicToRecentPage(iterator it)
{
    int size = musicOfRecentPage.size();
    for (int i = 0; i < size; ++i)
    {
        if (musicOfRecentPage[i] == it->getMusicUrl())
        {
            musicOfRecentPage.remove(i);
            break;
        }
    }
    musicOfRecentPage.push_back(it->getMusicUrl());
}

void CommonPage::addMusic(iterator it, MusicList& musicList, CommonPage* playPage, QMediaPlaylist* playlist)
{
    musicOfPage.push_back(it->getMusicUrl());
    if (playPage == this)
    {
        playlist->insertMedia(0, it->getMusicUrl());
        qDebug() << "播放列表中添加歌曲：" << it->getMusicUrl();
    }

    reFresh(musicList);
}

void CommonPage::addMusics(QList<QUrl> fileUrls, MusicList &musicList, CommonPage* playPage, QMediaPlaylist* playlist)
{
    if (fileUrls.size() == 0) return;

    for (int i = fileUrls.size() - 1; i >= 0; --i)
    {
        musicOfPage.push_back(fileUrls[i]);
        if (playPage == this)
        {
            playlist->insertMedia(0, fileUrls[i]);
            qDebug() << "播放列表中添加歌曲：" << fileUrls[i];
        }
    }

    reFresh(musicList);
}

void CommonPage::removeMusic(iterator it, MusicList &musicList, CommonPage* playPage, QMediaPlaylist* playlist)
{
    // 需要在musicOfPage和ui->pageMusicList中都移除该项
    int size = musicOfPage.size();
    int index = indexInMusicPage(it->getMusicUrl());
    if (index == -1) return;
    musicOfPage.remove(index);

    index = size - 1 - index;
    QListWidgetItem* item = ui->pageMusicList->takeItem(index);
    delete item;
    if (playPage == this)
    {
        playlist->removeMedia(index);
        qDebug() << "播放列表中移除歌曲：" << it->getMusicUrl();
    }

    if (musicOfPage.size() == 0)
    {
        setCommonPageImage(QPixmap(":/images/default_album_image.png"));
    }
    else if (index == 0)
    {
        setCommonPageImage(musicList.findMusicByMusicUrl(musicOfPage.back())->getCoverImage());
    }

    repaint();  // 触发窗口重绘事件paintEvent
}

int CommonPage::indexInMusicPage(const QUrl &url)
{
    int size = musicOfPage.size();
    for (int i = 0; i < size; ++i)
    {
        if (musicOfPage[i] == url)
            return i;
    }
    return -1;
}

void CommonPage::setItemIsLike(iterator it)
{
    int index = indexInMusicPage(it->getMusicUrl());
    if (index == -1) return;
    index = musicOfPage.size() - 1 - index;
//    qDebug() << "要修改图标的歌曲是：" << it->getMusicName() << ", 列表中的下标是：" << index;

    ListItemBox* listItemBox = (ListItemBox*)ui->pageMusicList->itemWidget(ui->pageMusicList->item(index));
    listItemBox->setIsLikeMusic(it->getIsLike());
}

void CommonPage::reFresh(MusicList &musicList)
{
    // 清除页面上显示的内容
    ui->pageMusicList->clear();

    // 重新添加歌曲条目
    for (int i = musicOfPage.size() - 1; i >= 0; --i)
    {
        auto it = musicList.findMusicByMusicUrl(musicOfPage[i]);
        if (it == musicList.end())
            continue;

        // 将歌曲信息更新到界面上
        ListItemBox* listItemBox = new ListItemBox(this);
        listItemBox->setMusicName(it->getMusicName());
        listItemBox->setMusicSinger(it->getMusicSinger());
        listItemBox->setMusicAlbum(it->getMusicAlbum());
        qint64 duration = it->getDuration();
        listItemBox->setDuration(QString("%1:%2").arg(duration / 1000 / 60, 2, 10, QChar('0')).arg(duration / 1000 % 60, 2, 10, QChar('0')));
        listItemBox->setCoverImage(it->getCoverImage());
        listItemBox->setIsLikeMusic(it->getIsLike());
        // 将ListItemBox对象放置到pageMusicList中
        QListWidgetItem* item = new QListWidgetItem(ui->pageMusicList);
        item->setSizeHint(QSize(listItemBox->width(), listItemBox->height()));
        ui->pageMusicList->setItemWidget(item, listItemBox);

        if (i == musicOfPage.size() - 1)
        {
            setCommonPageImage(it->getCoverImage());
        }

        connect(listItemBox, &ListItemBox::setIsLike, this, [=](bool isLike){
            // 发送信号通知MusicPlayer，更新歌曲状态，更新三个页面歌曲信息
//            qDebug() << "commonPage收到信号，发送信号给MusicPlayer，isLike: " << isLike << ", it: " << it;
            emit updateLikeMusic(isLike, it);
        });
    }

    // 触发窗口重绘事件paintEvent
//    update();
    repaint();
}

void CommonPage::addMusicToPlaylist(QMediaPlaylist *playlist)
{
    for (int i = musicOfPage.size() - 1; i >= 0; --i)
    {
        playlist->addMedia(musicOfPage[i]);
        qDebug() << "播放列表中添加歌曲：" << musicOfPage[i];
    }
}

void CommonPage::setStyleByIndex(int index, bool isPlaying, bool onlyAnimal)
{
    ListItemBox* listItemBox = (ListItemBox*)ui->pageMusicList->itemWidget(ui->pageMusicList->item(index));
    listItemBox->setItemStyle(isPlaying, onlyAnimal);
}

QUrl CommonPage::getMusicUrlByIndex(int index)
{
    if (index >= musicOfPage.size())
    {
        qDebug() << "没有此歌曲";
        return QUrl("");
    }
    return musicOfPage[musicOfPage.size() - 1 - index];
}

void CommonPage::readFromDB(MusicList& musicList)
{
    QSqlQuery query;
    if (pageType == LIKE_PAGE) query.prepare("SELECT musicUrl FROM LikePageMusicInfo;");
    else if (pageType == LOCAL_PAGE) query.prepare("SELECT musicUrl FROM LocalPageMusicInfo;");
    else if (pageType == HISTORY_PAGE) query.prepare("SELECT musicUrl FROM RecentPageMusicInfo;");
    if (!query.exec())
    {
        qDebug() << "数据库查询失败" << query.lastError().text();
        return;
    }
//    qDebug() << "读取数据库成功，恢复页面歌曲信息";

    while (query.next())
    {
        musicOfPage.push_back(QUrl("file:///" + query.value(0).toString()));
    }

    reFresh(musicList);

    if (pageType == HISTORY_PAGE) musicOfRecentPage = musicOfPage;
}

void CommonPage::writeToDB()
{
    // 因为要保持顺序不变，所以这里直接清空表，全部重新插入
    QSqlQuery query;
    if (pageType == LIKE_PAGE) query.prepare("DELETE FROM LikePageMusicInfo;");
    else if (pageType == LOCAL_PAGE) query.prepare("DELETE FROM LocalPageMusicInfo;");
    else if (pageType == HISTORY_PAGE) query.prepare("DELETE FROM RecentPageMusicInfo;");
    if (!query.exec())
    {
        qDebug() << "清空表失败：" << query.lastError().text();
        return;
    }

    // 重新插入数据
    if (pageType == HISTORY_PAGE) musicOfPage.swap(musicOfRecentPage);
    for (auto url : musicOfPage)
    {
        if (pageType == LIKE_PAGE) query.prepare("INSERT INTO LikePageMusicInfo (musicUrl) VALUES (?);");
        else if (pageType == LOCAL_PAGE) query.prepare("INSERT INTO LocalPageMusicInfo (musicUrl) VALUES (?);");
        else if (pageType == HISTORY_PAGE) query.prepare("INSERT INTO RecentPageMusicInfo (musicUrl) VALUES (?);");
        query.addBindValue(url.toLocalFile());
        if (!query.exec())
        {
            qDebug() << "插入失败：" << query.lastError().text();
            return;
        }
        qDebug() << "插入music信息：" << url;
    }
}

void CommonPage::on_addLocalBtn_clicked()
{
    emit addLocalMusic();
}
